package cn.edu.scau.nursingcenter.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;

import cn.edu.scau.nursingcenter.bean.ResultBean;
import cn.edu.scau.nursingcenter.config.Audience;
import cn.edu.scau.nursingcenter.util.JWTTokenUtil;
import io.swagger.models.HttpMethod;

/**
  * 登录拦截器 检查token 验证是否过期
 * @author feng
 *
 */
@Component
public class LoginInterceptor implements HandlerInterceptor{

	@Autowired
	private Audience audience;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		//使用jwt
		if(HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
			return true;
		}
		//获取请求头token内容
		final String token = request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY);
		//验证token的合法性，通过则可以继续访问指定的链接请求
		//System.err.println(token);
		if(null != token && !JWTTokenUtil.isExpiration(token, audience.getBase64Secret()) ) {
			return true;
		}
		//以下代码，是不通过的情况下，给请求者对应的信息提示
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
		//JSONObject jsonObject = new JSONObject();
		
		ResultBean resultBean = new ResultBean(5009, false, "登录已过期，请重新登录...", "");
		PrintWriter writer = response.getWriter();
		writer.write(JSON.toJSONString(resultBean));
		//jsonObject.put("r", resultBean);
		//response.getOutputStream().write(jsonObject.toString().getBytes("UTF-8"));
		return false;
	}
}
